package controllers

import (
	"bytes"
	"encoding/binary"
	"github.com/astaxie/beego"
	"github.com/taka-wang/modbus"
	"log"
	"time"
)

type MainController struct {
	beego.Controller
}

func (c *MainController) Get() {
	c.Data["data"] = modbusdata()
	c.TplName = "index.tpl"
}

func modbusdata() []uint16 {
	handler := modbus.NewTCPClientHandler("172.16.1.8:502")
	handler.Timeout = 10 * time.Second
	handler.SlaveID = 0x00
	//handler.Logger = log.New(os.Stdout, "Fsyx: ", log.LstdFlags)
	// Connect manually so that multiple requests are handled in one connection session
	err := handler.Connect()
	if err != nil {
		log.Fatal(err)
	}
	defer handler.Close()
	client := modbus.NewClient(handler)

	res, err := client.ReadHoldingRegisters(99, 10)
	if err != nil {
		log.Fatal(err)
	}
	return Dcode(res)

}

//byte to Uint16
func Dcode(res []byte) (results []uint16) {
	b_buf := bytes.NewBuffer(res)
	u16 := make([]uint16, len(res)/2)
	binary.Read(b_buf, binary.BigEndian, &u16)
	return u16
}
